package com.yzf.demo.demo.Thread;

/**
 * Created by 于占峰 on 2020/4/1/001.
 * ThredLocal示例
 */
public class ThredLocalDemo {

    private static Integer sum = 0;

    public static final ThreadLocal<Integer> local = new ThreadLocal<Integer>() {
        //重写initialValue方法
        protected Integer initialValue() {
            return 0;//初始值
        }
    };

    /**
     * 因为线程的先后运行顺序不同,每个线程拿到的变量值随着先后顺序变化而不一定,
     * 存在相互干扰,数据的不正确性;
     */
    public static void main3(String[] args) {
        //定义五个线程
        Thread[] threads = new Thread[5];
        for (int i = 0; i < 5; i++) {
            threads[i] = new Thread(() -> {
                sum += 5;
                System.out.println(Thread.currentThread().getName() + "--->" + sum);
            }, "Thred-" + i);
        }
        //遍历运行每个线程
        for (Thread thread : threads) {
            thread.start();
        }

    }


    public static void main(String[] args) {
        //定义五个线程
        Thread[] threads = new Thread[5];
        for (int i = 0; i < 5; i++) {
            threads[i] = new Thread(() -> {
                //sum+=5;
                //拿到初始值
                int num = local.get();
                num += 5;
                local.set(num);
                System.out.println(Thread.currentThread().getName() + "--->" + sum);
            }, "Thred-" + i);
        }
        //遍历运行每个线程
        for (Thread thread : threads) {
            thread.start();
        }
    }
}
